//这个文件专门用来存放关于用户、用户反馈的所有接口

const user = require("koa-router")();
const { exec } = require("../util/db");
const bodyparser = require("koa-bodyparser");
user.use(bodyparser()); //调用这个中间件 就可以拿到前端post过来的数据
const wxkey = require("../util/wxkey.js");
const { httpcli } = require("gohttp");
const token = require("titbit-token");

// get请求
// http://localhost:3000/user/list
user.get("/list", async (ctx) => {
  let obj = ctx.query;
  console.log("======", obj);
  if (JSON.stringify(obj) == "{}") {
    let selectSql = `select * from user`;
    let res = await exec(selectSql);
    ctx.body = res;
  } else {
    let inquiry = "";
    for (var p in obj) {
      if (inquiry != "") [(inquiry += "and")];
      inquiry += ` ${p}='${obj[p]}'`;
    }
    let selectSql = `select * from user where${inquiry}`;
    console.log("----", selectSql);
    let res = await exec(selectSql);
    ctx.body = res;
  }
  // console.log('ctx',ctx)
  // let selectSql = `select * from user`
  // let res = await exec(selectSql)
  // ctx.body = res
});

// 后台用户登录
// http://localhost:3000/user/login
user.post("/login", async (ctx) => {
  let obj = ctx.request.body;
  let selectSql = `select * from managers where userName='${obj.userName}' and password='${obj.password}'`;
  let res=await exec(selectSql);
  ctx.body = res;
});

// del请求
// http://localhost:3000/user/del
user.delete("/del", async (ctx) => {
  let obj = ctx.request.body;
  console.log("deluser", obj);
  let deleteSql = `delete from user where userId='${obj.userId}'`;
  let deleteSql2 = `delete from feedback where userId='${obj.userId}'`;
  await exec(deleteSql2);
  await exec(deleteSql);
  ctx.body = "删除成功啦";
});

// post请求
// http://localhost:3000/user/customer
user.post("/customer", async (ctx) => {
  let result = tok.verify(ctx.request.header.authorization);
  let obj = ctx.request.body;
  let user = {
    userId: result.data.openid,
    userName: obj.userName,
    headPhoto: obj.headPhoto,
  };
  if (result.ok) {
    let selectSql = `select * from user`;
    let users = await exec(selectSql);
    let flag = false;
    // 判断数据库user表中是否含有请求中的openid
    for (key in users) {
      if (users[key].userId == result.data.openid) {
        flag = true;
      }
    }
    // 如果没有，则进行插入
    if (flag == false) {
      let insertSql = `insert into user(userId,userName,headPhoto) values('${result.data.openid}','${obj.userName}','${obj.headPhoto}')`;
      console.log(insertSql);

      let res = await exec(insertSql);
      ctx.body = user;
    } else {
      //如果有，则进行更新
      let updateSql = `update user set userName='${obj.userName}',
            headPhoto='${obj.headPhoto}' where userId='${result.data.openid}'`;
      await exec(updateSql);
      ctx.body = user;
    }
  } else {
    ctx.status = 500;
    ctx.body = JSON.stringify("出错啦~登录失败");
  }
});

// 会话登录验证
let tok = new token({
  // token解密验证3600秒即为超时（token有效期，单位为秒）
  expires: 31536000,
  // 必须是32位字符
  key: "ashdisjow82910wjsidhaolp9748wj1s", //加密字符

  // 必须是16位字符
  iv: "18dhsjaosjwosnvj", //干扰项
});
// 返回token值
user.get("/login/:code", async (ctx) => {
  let code = ctx.params.code;
  console.log(code);
  let auth_url =
    `https://api.weixin.qq.com/sns/jscode2session` +
    `?appid=${wxkey.appid}&secret=${wxkey.secret}` +
    `&js_code=${code}&grant_type=authorization_code`;

  let ret = await httpcli.get(auth_url).then((res) => {
    return res.json();
  });

  console.log(ret);

  if (!ret.openid) {
    ctx.status = 500;
    ctx.body = JSON.stringify(ret);
    return;
  }
  ctx.body = tok.make(ret);
});

// 判断一下是不是第一次登陆，如果不是第一次登录则把用户的其他信息返回
user.get("/customer", async (ctx) => {
  // console.log(ctx.request.header.authorization)
  let result = tok.verify(ctx.request.header.authorization);
  if (result.ok) {
    let selectSql = `select * from user where userId='${result.data.openid}'`;
    let res = await exec(selectSql);
    ctx.body = res;
  } else {
    ctx.status = 500;
    ctx.body = result;
  }
});

function getRandom() {
  let code = "";
  for (var i = 0; i < 6; i++) {
    code += parseInt(Math.random() * 10);
  }
  return code;
}

// 以下是关于用户反馈的所有接口
// http://localhost:3000/user/feedback
user.post("/feedback", async (ctx) => {
  let obj = ctx.request.body;
  let feedbackId = getRandom();
  let feedbackTime = Date.now();
  console.log(feedbackTime);
  let insertSql = `insert into feedback(userId,feedbackId,feedbackContent,feedbackTime) values('${obj.userId}','${feedbackId}','${obj.feedbackContent}','${feedbackTime}')`;
  await exec(insertSql);
  ctx.body = "插入成功啦";
});

// http://localhost:3000/user/feedback
user.get("/feedback", async (ctx) => {
  let selectSql = `select * from feedback`;
  let res = await exec(selectSql);
  ctx.body = res;
});

// http://localhost:3000/user/feedback
user.delete("/feedback", async (ctx) => {
  let obj = ctx.request.body;
  console.log("delfeedback", obj);
  let deleteSql = `delete from feedback where feedbackId='${obj.feedbackId}'`;
  await exec(deleteSql);
  ctx.body = "删除成功啦";
});

module.exports = user;
